from datetime import datetime
import logging
import os
from ConfigManager import ConfigManager

def setup_logger():
    # 获取当前日期和时间，并格式化为 YYYYMMDDHHMM
    current_datetime = datetime.now().strftime("%Y%m%d")   
         
    cm = ConfigManager()
    config = cm.get_merged_config()
    raw_path = config["logging"]["dir"]
    log_dir = os.path.expandvars(raw_path)
    # 构建日志文件的相对路径
    log_levels = ['info', 'error']
    log_file_paths = {level: os.path.join(log_dir, f'{level}_{current_datetime}.log') for level in log_levels}
    
    # 确保目录存在
    os.makedirs(os.path.dirname(log_file_paths['info']), exist_ok=True)

    # 创建 Logger
    logger = logging.getLogger('security_check_logger')
    if not logger.hasHandlers():  # 检查是否已经有 Handler
        logger.setLevel(logging.INFO)  # 设置日志级别为INFO

        # 创建并配置每个日志处理器
        for level in log_levels:
            handler = logging.FileHandler(log_file_paths[level], mode='a', encoding='utf-8')
            handler.setLevel(getattr(logging, level.upper()))
            formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s:%(lineno)d - %(message)s')
            handler.setFormatter(formatter)
            logger.addHandler(handler)

        # 可选：添加控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        console_formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s:%(lineno)d - %(message)s')
        console_handler.setFormatter(console_formatter)
        logger.addHandler(console_handler)

    return logger

# 示例调用
if __name__ == "__main__":
    logger = setup_logger()
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")
    logger.critical("This is a critical message")